package com.xzy.springcloud.controller;



import com.xzy.springcloud.pojo.CommonResult;
import com.xzy.springcloud.pojo.Payment;
import com.xzy.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class PaymentCpmtroller {

    @Autowired
    PaymentService service;


    @Autowired
    DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String servicePort;

    @PostMapping("/payment/create")
    //这里加requestbody是因为消费者使用restTemplate调用时封装了一个payment(对象被封装在请求体中)
    public CommonResult create(@RequestBody Payment payment){
        int result = service.create(payment);

        log.info("------>插入："+result);
        if(result>0){
            return new CommonResult(200,"插入成功,:serverPort"+servicePort,result);
        }else {
            return new CommonResult(444,"插入失败,:serverPort"+servicePort,null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getbyId(@PathVariable("id") Long id){
        Payment result = service.getByid(id);

        log.info("------>查询出："+result);
        if(result != null){
            return new CommonResult(200,"查询成功,:serverPort"+servicePort,result);
        }else {
            return new CommonResult(444,"查询失败，查询ID"+id+"serverPort:"+servicePort,null);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        //获取在注册中心注册的微服务
        List<String> services = discoveryClient.getServices();

        for (String s : services) {
            log.info(s);
        }

        //获取该名称的微服务实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances) {
            log.info(instance.getHost() + "  " + instance.getPort());

        }


        return this.discoveryClient;
    }


}
